﻿var CTX = {
    initialize: function () {
        jQuery(CTX.Util.is.types).each(function (index, c) {
            CTX.Util.is[c] = (function (type) {
                return function (obj) {
                    return Object.prototype.toString.call(obj) == "[object " + type + "]";
                };
            })(c);
        });
    }
};
CTX.Constants = {
    WIDGET_INFO: "widgetinfo"
};
CTX.Util = {
    is: { types: ["Array", "RegExp", "Date", "Number", "String", "Object", "HTMLDocument"] },
    isInMSAjaxMode: function () {
        return typeof (Sys) != "undefined" && typeof (Sys.WebForms) != "undefined";
    },
    addPageLoaded: function (pageLoadedEvent) {
        if (this.isInMSAjaxMode()) {
            Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(function (sender, e) {
                pageLoadedEvent(e, sender);
            });
        }
        else {
            $(document).ready(function (e) {
                pageLoadedEvent(e);
            });
        }
    }
};

CTX.Widgets = {
    attributes: {
        COLUMN_ID: "columnid",
        WIDGET_TYPE_ID: "widgettypeid",
        WIDGET_ID: "widgetid"
    },
    pageId: null,
    options: null,
    allWidgetInfos: [],
    initialize: function (_pageid, columnClass, widgetClass, newWidgetClass, newWidgetTitleClass, handleClass, lockWidgetClass, placeholderClass, columnPostBackTrigger) {
        this.allWidgetInfos = [];
        this.pageId = _pageid;
        this.options = {
            pageId: _pageid,
            columnClass: columnClass,
            widgetClass: widgetClass,
            newWidgetClass: newWidgetClass,
            newWidgetTitleClass: newWidgetTitleClass,
            handleClass: handleClass,
            lockWidgetClass: lockWidgetClass,
            placeholderClass: placeholderClass,
            columnPostbackTrigger: columnPostBackTrigger
        };

        $("." + columnClass).each(function () {
            var column = $(this);
            column.find("." + handleClass).each(function (index, widgethandle) {
                var widgetInfo = CTX.Widgets.WidgetInfo.getInstance(
                                $(widgethandle).attr(CTX.Widgets.attributes.WIDGET_ID),
                                $(widgethandle).attr(CTX.Widgets.attributes.WIDGET_TYPE_ID),
                                column.attr(CTX.Widgets.attributes.COLUMN_ID),
                                _pageid,
                                index
                         );
                CTX.Widgets.allWidgetInfos.push(widgetInfo);
                $(widgethandle).data(CTX.Constants.WIDGET_INFO, widgetInfo);
            });
        });

        $("." + newWidgetClass).each(function () {
            var widgetInfo = CTX.Widgets.WidgetInfo.getInstance(
                                    null,
                                    $(this).attr(CTX.Widgets.attributes.WIDGET_TYPE_ID),
                                    null,
                                    _pageid,
                                    -1);
            $(this).data(CTX.Constants.WIDGET_INFO, widgetInfo)
        });

        this.initDragDrop(columnClass, widgetClass, newWidgetClass, newWidgetTitleClass, handleClass, lockWidgetClass, placeholderClass, columnPostBackTrigger);
    },
    initializeWithOptions: function (_options) {
        this.initialize(_options.pageId, _options.columnClass, _options.widgetClass, _options.newWidgetClass,
                                 _options.newWidgetTitleClass, _options.handleClass, _options.lockWidgetClass,
                                 _options.placeholderClass, _options.columnPostBackTrigger);
    },
    reinitialize: function () {
        this.initializeWithOptions(this.options);
    },
    initDragDrop: function (columnClass, widgetClass, newWidgetClass, newWidgetTitleClass, handleClass, lockWidgetClass, placeholderClass, columnPostBackTrigger) {

        var allColumns = jQuery("." + columnClass);
        //Destroy the old sortable data
        allColumns.each(function () {
            var plugin = jQuery(this).data("sortable");
            if (plugin) {
                plugin.destroy();
            }
        });

        var itemsSelector = (lockWidgetClass == null)
                                    ? ("." + widgetClass)
                                    : ("." + widgetClass + ":not(." + lockWidgetClass + ")");
        // Init the column's sortable
        allColumns.sortable({
            connectWith: "." + columnClass,
            cursor: "move",
            handle: "." + handleClass,
            placeholder: placeholderClass,
            items: itemsSelector,
            tolerance: "pointer",
            start: function (event, ui) {
                ui.placeholder.height(ui.item.height());
            },
            change: function (event, ui) {

                if (ui.item != undefined) {
                    ui.placeholder.height(ui.item.height());
                }
                else {
                    ui.placeholder.height(200);
                }
            },
            stop: function (event, ui) {
                // Drag a new widget
                if (ui.item.hasClass(newWidgetClass)) {
                    var newWidgetTitle = ui.item.find("." + newWidgetTitleClass).text();
                    var newWidgetSnap = CTX.Widgets.createNewWidgetSnap(newWidgetTitle);
                    ui.item.replaceWith(newWidgetSnap);
                    var widgetInfo = CTX.Widgets.WidgetInfo.getInstance(
                                    null,
                                    $(ui.item).attr(CTX.Widgets.attributes.WIDGET_TYPE_ID),
                                    null,
                                    CTX.Widgets.pageId,
                                    -1);
                    CTX.Widgets.Actions.onAddWidget(widgetInfo, function (data) {

                    });
                }
                // Move widget from others
                else {
                    var column = $(ui.item).parents("." + columnClass);
                    var _fromWidgetInfo = $(ui.item).data(CTX.Constants.WIDGET_INFO);
                    var _toWidgetInfo = CTX.Widgets.WidgetInfo.copyFrom(_fromWidgetInfo);
                    _toWidgetInfo.ColumnID = column.attr(CTX.Widgets.attributes.COLUMN_ID);
                    _toWidgetInfo.Index = column.find("." + handleClass).index(ui.item);
                    CTX.Widgets.Actions.onMoveWidget(_fromWidgetInfo, _toWidgetInfo, function (data) {

                    });
                }
            }
        });

        //Init drag new widget to column
        $("." + newWidgetClass).draggable({
            connectToSortable: "." + columnClass,
            helper: "clone",
            tolerance: "pointer"
        });
    },
    createNewWidgetSnap: function (widgetTitle) {
        return $('<div class="widgetContainer">'
                        + '<div class="widgetHeader">'
                        + '<span class="widgetTitle">&nbsp;</span>'
                        + '<div class="widgetHeaderButton">'
                        + '<a id="collapseWidgetAnchor" class="editwidget widget_collapse"></a>'
                        + '</div>'
                        + '</div>'
                        + '<div class="widgetHolder">'
                        + 'loading ...'
                        + '</div>'
                        + '<div class="widgetFooter">'
                        + '</div>'
                        + '</div>').find(".widgetTitle").html(widgetTitle).parents(".widgetContainer");
    },
    Actions: {
        onAddWidget: function (_widgetInfo, callback) {
            CTX.Services.Widgets.addWidget(_widgetInfo, function (data) {
                CTX.Widgets.allWidgetInfos.push(_widgetInfo);
                callback(data);
            });
            return this;
        },
        onMoveWidget: function (_fromWidgetInfo, _toWidgetInfo, callback) {
            CTX.Services.Widgets.moveWidget(_fromWidgetInfo, _toWidgetInfo, function (data) {
                var index = $(CTX.Widgets.allWidgetInfos).index(_fromWidgetInfo);
                CTX.Widgets.allWidgetInfos.slice(index, 1);
                CTX.Widgets.allWidgetInfos.push(_toWidgetInfo);
                callback(data);
            });
            return this;
        }
    }
};

CTX.Widgets.WidgetInfo = function (_id, _typeid, _columnid, _pageid, _index) {
    this.ID = _id;
    this.ColumnID = _columnid;
    this.PageID = _pageid;
    this.Index = _index;
    this.WidgetTypeId = _typeid;
}
CTX.Widgets.WidgetInfo.getInstance = function (_id, _typeid, _columnid, _pageid, _index) {
    return new CTX.Widgets.WidgetInfo(_id, _typeid, _columnid, _pageid, _index);
};
CTX.Widgets.WidgetInfo.copyFrom = function (_fromWidgetInfo) {
    return new CTX.Widgets.WidgetInfo(_fromWidgetInfo.ID,
                                               _fromWidgetInfo.WidgetTypeId,
                                               _fromWidgetInfo.ColumnID,
                                               _fromWidgetInfo.PageID,
                                               _fromWidgetInfo.Index);
};

CTX.Services = {
    Widgets: {
        addWidget: function (_widgetInfo, callback) {
        },
        removeWidget: function (_widgetInfo, callback) {
        },
        moveWidget: function (_fromWidgetInfo, _toWidgetInfo, callback) {
        }
    }
};

CTX.initialize();
CTX.Util.addPageLoaded(function (event, sender) {
    CTX.Widgets.initialize(1, "ui-columnholder", "widgetContainer", "newwidgetitem", "newwidgetitemtitle", "widgetHeader", "locked", "widgetholder", ".refreshButton");
});
$(".LockButton").click(function () {
    $(".column:first").find(".widgetContainer:first").addClass("locked");
    CTX.Widgets.reinitialize();
});
$(".UnLockButton").click(function () {
    $(".column:first").find(".widgetContainer:first").removeClass("locked");
});